/* eslint-disable */

import axios from 'axios'
import qs from 'qs'
import {
  message
} from 'antd'
import utils from '@/utils/utils'
import store from '@/store'

import {
  actions
} from '@/components/Login'
import loading from '@/components/ajax-loading'

function refresh() {
  loading.hide()
  axios.unLoading = false
}


axios.unLoading = false
// 默认  基础路径
axios.defaults.baseURL = process.env.NODE_ENV === 'development' ? '/api' : ''
// 添加请求拦截器
axios.interceptors.request.use(config => {
  // console.log('config', config.data);

  if (config.data) {
    if (typeof config.data === 'string') {
      config.data += `&_=${+new Date()}`
    } else {
      config.data['_'] = +new Date()
      config.data = qs.stringify(config.data)
    }
  } else if (/\?|=/g.test(config.url)) {
    config.url = config.url + `&_=${+new Date()}`
  }
  // console.log('config', config);
  
  return config
}, error => {
  refresh()
  // 对请求错误做些什么
  return Promise.reject(error);
})



// 响应拦截
axios.interceptors.response.use(function (res) {
  refresh()
  res = res.data
  let _success = (res.result === 'success' || res.code == '200' || res.code == '403' || res.code == '500' || res.code == '302' || res.code == '404' || res.code == '406')
  if (!_success && (res.message || res.msg)) {
    message.warning(res.message || res.msg)
  }

  if (res.code === 302 || res.message === '请先登录') {
    store.dispatch(actions.signOut({}))
  }
  return res

}, (error) => {
  if (!(error.message === 'cancel')) {
    refresh()
  }
  const RESPONSE = error.response
  if (RESPONSE && RESPONSE.status === 404) {
    message.warning('请检查网络连接是否正常！')
  }
  return {
    _success: false,
    message: '请检查网络连接是否正常！',
    canceled: error.message === 'cancel'
  }
})

export default axios

/* eslint-enable */